package com.example.sneakerappforme1105;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.example.sneakerappforme1105.bean.Cart;
import com.example.sneakerappforme1105.bean.User;
import com.example.sneakerappforme1105.constant.NetConst;
import com.example.sneakerappforme1105.dao.CartDao;
import com.example.sneakerappforme1105.dao.UserDao;
import com.example.sneakerappforme1105.util.ToastUtil;
import com.example.sneakerappforme1105.util.ViewUtil;

import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SignUpActivity extends AppCompatActivity {
    private EditText et_signUp_username;
    private EditText et_signUp_password;
    private UserDao userDao;
    private CartDao cartDao;    // 注册完一个用户,插入一条购物车id
    private final String TAG = "signup";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);

        et_signUp_username = findViewById(R.id.et_signUp_username);
        et_signUp_password = findViewById(R.id.et_signUp_password);
        userDao = MainApplication.getInstance().getAppDatabase().userDao();
        cartDao = MainApplication.getInstance().getAppDatabase().cartDao();


        findViewById(R.id.button_confirm).setOnClickListener(view -> {
            String username = et_signUp_username.getText().toString();
            String password = et_signUp_password.getText().toString();

            if(username.equals("") || password.equals("")){
                Toast.makeText(this,"用户名或密码不能为空(!_!)",Toast.LENGTH_SHORT).show();
            }else if(password.length()>=8){



                // 检查用户名是否存在，向后端发送请求
                checkIfUsernameExists(username, password);


            }else{
                Toast.makeText(this, "密码长度小于8位", Toast.LENGTH_SHORT).show();
            }







        });

        findViewById(R.id.button_exit).setOnClickListener(view -> finish());    // 已经有账号返回登录即可
    }

    private void checkIfUsernameExists(String username, String password) {
        OkHttpClient client = new OkHttpClient();





        Request request = new Request.Builder()
                .url(NetConst.HTTP_PREFIX+"user/check?userName="+username) // 替换为你的API地址
                .get()
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                System.out.println("请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    try {
                        //继续处理注册
                        JSONObject jsonResponse = new JSONObject(responseBody);
                        if(jsonResponse.has("data")){
                            JSONObject dataObject = jsonResponse.getJSONObject("data");
                            if(dataObject.has("exists")){
                                boolean nameExists = dataObject.getBoolean("exists");
                                if (nameExists) {
                                    runOnUiThread(() -> {
                                        et_signUp_username.setText("");
                                        Toast.makeText(SignUpActivity.this, "用户名已存在，请换个名字", Toast.LENGTH_SHORT).show();
                                    });
                                } else {
                                    // 用户名不存在，进行注册
                                    registerUser(username, password);   // 后端请求
                                }
                            }
                        }



                    } catch (Exception e) {
                        e.printStackTrace();
                        runOnUiThread(() -> Toast.makeText(SignUpActivity.this, "检查重名错误", Toast.LENGTH_SHORT).show());
                    }

                }else {
                    runOnUiThread(() -> Toast.makeText(SignUpActivity.this, "服务器错误，请稍后再试", Toast.LENGTH_SHORT).show());
                }
            }
        });


    }


    private void registerUser(String username, String password) {

        OkHttpClient client = new OkHttpClient();


        RequestBody body = new FormBody.Builder()
                .add("username", username)
                .add("password", password)
                .build();

        Request request = new Request.Builder()
                .url(NetConst.HTTP_PREFIX+"user/register?userName="+username+"&passWord="+password) // 替换为你的API地址
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> Toast.makeText(SignUpActivity.this, "注册失败，请稍后再试", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    runOnUiThread(() -> {
                        Toast.makeText(SignUpActivity.this, "注册成功，为您跳转到登录页面^_^", Toast.LENGTH_LONG).show();
                        finish(); // 注册成功，跳转
                    });
                } else {
                    runOnUiThread(() -> Toast.makeText(SignUpActivity.this, "注册失败，服务器错误", Toast.LENGTH_SHORT).show());
                }
            }
        });

    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG,"从注册页面返回");
    }




}